import { getGroupList } from '@/services/groupManage';
import { getUserInfoById, updateUserInfo, uploadAvatar } from '@/services/groupNumber';
import { UploadOutlined } from '@ant-design/icons';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import { useModel } from 'umi';
import { Avatar, Button, Col, Form, message, Row, Select, Upload, UploadProps } from 'antd';
import ImgCrop from 'antd-img-crop';
import { useForm } from 'antd/es/form/Form';
import { RcFile } from 'antd/es/upload';
import React, { useEffect, useState } from 'react';
import './index.less';
const Index: React.FC = (props) => {
  const [form] = useForm();
  const [imageUrl, setImageUrl] = useState('');
  const [userInfo, setUserInfo] = useState({});
  //部门下拉框
  const [groupOptions, setGroupOptions] = useState([]);
  const formLayout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 12,
    },
  };

  const onSubmit = async (values) => {
    values.id = userInfo.id;
    const res = await updateUserInfo(values);
    if (res.code == '0') {
      message.success('更新成功');
    }
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传png/jpeg!');
    }
    // 限制文件大小 小于10m
    const isFile10M = file.size / (1024 * 1024) > 10;
    if (isFile10M) {
      message.error('文件大小不得超于10M，请修改后重新上传');
      return false;
    }
    return isJpgOrPng;
  };
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  const propsImg: UploadProps = {
    name: 'file',
    headers: {
      authorization: 'authorization-text',
    },
    showUploadList: false,
    beforeUpload: beforeUpload,
    customRequest: (options) => {
      getBase64(options.file as RcFile, (url) => {
        const userId = sessionStorage.getItem('userId');
        const params = {
          id: userId,
          avatarBase64: url,
        };
        uploadAvatar(params).then((res) => {
          if (res.code == '0') {
            setImageUrl(url);
            message.success(`头像上传成功！`);
          } else {
            message.error(`头像上传失败！`);
          }
        });
      });
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
      } else if (info.file.status === 'error') {
        message.error(`头像上传异常`);
      }
    },
  };

  //根据id获取信息
  const getUserInfo = async (id: any) => {
    const res = await getUserInfoById({ id });
    if (res.code == '0') {
      const info = res.data;
      form.setFieldsValue(info);
      setUserInfo(info);
      setImageUrl(info.avatar);
    } else {
      message.error(res.message);
    }
  };

  useEffect(() => {
    //获取组list
    getGroupList().then(async (res) => {
      let groupList = [];
      if ((res.code = '0')) {
        if (res.data.length > 0) {
          for (let i in res.data) {
            groupList.push({
              value: res.data[i].id,
              label: res.data[i].groupName,
            });
          }
          await setGroupOptions(groupList);
        }
      } else {
        message.error(res.message);
      }
    });
    const userId = sessionStorage.getItem('userId');
    if (!!userId) {
      getUserInfo(userId);
    }
  }, []);

  return (
    <PageContainer
      header={{
        title: '修改资料',
      }}
    >
      <ProForm
        form={form}
        layout="horizontal"
        {...formLayout}
        onFinish={onSubmit}
        submitter={{
          render: (_, dom) => {
            return <div style={{ display: 'flex', justifyContent: 'center' }}>{dom[1]}</div>;
          },
        }}
      >
        <Row>
          <Col span={12}>
            <Avatar className="avatarDiv" size={150} src={imageUrl} />
            <ImgCrop rotationSlider cropShape="round" modalTitle="编辑图片">
              <Upload className="updateAvatar" {...propsImg}>
                <Button icon={<UploadOutlined />}> 更换头像</Button>
              </Upload>
            </ImgCrop>
          </Col>
          <Col span={12}></Col>
          <Col span={12}>
            <div className="baseData">基本资料</div>
            <Form.Item
              label="部门"
              name="groupId"
              // rules={[
              //   {
              //     required: true,
              //     message: '部门必选！',
              //   },
              // ]}
            >
              <Select placeholder="请选择" options={groupOptions} allowClear disabled />
            </Form.Item>
            <ProFormText
              // rules={[
              //   {
              //     required: true,
              //     message: '用户名必填！',
              //   },
              // ]}
              width="md"
              name="name"
              placeholder="请输入用户名"
              label="用户名"
              disabled
            />
            <ProFormText
              width="md"
              name="idNum"
              // rules={[
              //   {
              //     required: true,
              //     message: '身份证必填！',
              //   },
              // ]}
              placeholder="请输入身份证"
              label="身份证"
              disabled
            />
            <ProFormText width="md" name="phoneNum" placeholder="请输入手机号" label="手机号" />
          </Col>
        </Row>
      </ProForm>
    </PageContainer>
  );
};

export default Index;
